package com.example.mapstruct.converter;

import com.example.mapstruct.entity.dto.Department;
import com.example.mapstruct.entity.dto.Employee;
import com.example.mapstruct.entity.dto.GoodDTO;
import com.example.mapstruct.entity.po.GoodCategoryPO;
import com.example.mapstruct.entity.po.GoodPO;
import com.example.mapstruct.entity.vo.GoodVO;
import org.mapstruct.*;
import org.mapstruct.factory.Mappers;

import javax.xml.crypto.Data;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: good的转换
 * @author: linx
 * @create: 2021-09-22 15:20
 */
//componentModel设置为spring是为了符合spring的编程风格，可以直接通过@Autowired注入方式使用
@Mapper(componentModel = "spring")
public interface GoodConverter {
    GoodConverter goodConverter = Mappers.getMapper(GoodConverter.class);

    @Mappings({
            @Mapping(source = "goodId", target = "id"),
            @Mapping(source = "goodName", target = "name"),
            @Mapping(source = "goodStock", target = "stock"),
            // @Mapping(source = "category", target = "category") 字段相同的可以不写映射关系也能映射
            @Mapping(target = "status", ignore = true)
    })
    GoodVO goodDTO2GoodVO(GoodDTO goodDTO);

    @InheritInverseConfiguration
    GoodDTO goodVO2GoodDTO(GoodVO goodVO);

    List<GoodVO> goodDTO2GoodVO(List<GoodDTO> list);

    @InheritInverseConfiguration
    List<GoodDTO> goodVO2GoodDTO(List<GoodVO> list);

    @Mappings({
            @Mapping(source = "goodPO.goodId", target = "id"),
            @Mapping(source = "goodPO.goodName", target = "name"),
            @Mapping(source = "goodPO.goodStock", target = "stock"),
            @Mapping(source = "goodPO.goodStatus", target = "status", qualifiedByName = "converterStatus"),
            @Mapping(source = "goodCategoryPO.category", target = "category")
    })
    GoodVO goodPOAndGoodCategoryPO2GoodVO(GoodCategoryPO goodCategoryPO, GoodPO goodPO);


    /**
     * 自定义status从int转boolean的逻辑
     *
     * @param status
     * @return
     */
    @Named("converterStatus")
    default Boolean converterStatus(Integer status) {
        return status == 1;
    }


    /**
     * Map to  Bean
     *
     * @param map
     * @return
     */

    @Mapping(target = "department", ignore = true)
    Employee fromMap(Map<String, String> map);


    @AfterMapping
    default void finishEmployee(@MappingTarget Employee employee, Map<String, String> map) {
        employee.setDepartment(fromMapToDepartment(map));
    }

    @Mapping(target = "id", source = "did")
    @Mapping(target = "name", source = "dname")
    Department fromMapToDepartment(Map<String, String> map);


    @MapMapping(
            valueDateFormat = "yyyy-MM-dd"
    )
    Map<String, String> toMap(Map<String, Date> dateMap);


}
